// stores/staffStore.js
import { defineStore } from "pinia";
import { ref, computed } from "vue";
import {
  getStaffList,
  createStaff,
  updateStaff,
  deleteStaff,
  getAllStaffDetails,
} from "@/api/staffApi";

export const useStaffStore = defineStore("staff", () => {
  // State
  const staffList = ref([]);
  const currentStaffId = ref(null);
  const isLoading = ref(false);
  const error = ref(null);

  // Getters
  const currentStaff = computed(() => {
    return (
      staffList.value.find((staff) => staff.id === currentStaffId.value) || null
    );
  });

  const hasStaff = computed(() => staffList.value.length > 0);

  // Actions
  const loadStaffList = async () => {
    isLoading.value = true;
    error.value = null;
    try {
      const response = await getAllStaffDetails();
      // 根据后端返回的数据结构调整
      if (response.code === 200 && response.data && response.data.data) {
        staffList.value = response.data.data || [];
        if (staffList.value.length > 0) {
          currentStaffId.value = staffList.value[0].id;
        }
        return staffList.value;
      } else {
        throw new Error(response.message || "数据格式错误");
      }
    } catch (err) {
      error.value = err.message || "加载员工列表失败";
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  // 新增：本地添加员工（不调用API）
  const addStaffLocal = (staffData) => {
    staffList.value.push(staffData);
    currentStaffId.value = staffData.id;
    return staffData;
  };

  // 修改：只在保存时调用API创建员工
  const createStaffAPI = async (staffData) => {
    try {
      const response = await createStaff(staffData);
      if (response.code === 200) {
        const newStaff = response.data || staffData;
        // 更新本地数据，用API返回的数据替换本地临时数据
        const index = staffList.value.findIndex(
          (staff) => staff.id === staffData.id
        );
        if (index !== -1) {
          staffList.value[index] = newStaff;
        }
        currentStaffId.value = newStaff.id;
        return newStaff;
      } else {
        throw new Error(response.message || "创建员工失败");
      }
    } catch (err) {
      error.value = err.message || "创建员工失败";
      throw err;
    }
  };

  const updateStaffData = async (staffData) => {
    try {
      const response = await updateStaff(staffData);
      if (response.code === 200) {
        const updatedStaff = response.data || staffData;

        const index = staffList.value.findIndex(
          (staff) => staff.id === updatedStaff.id
        );
        if (index !== -1) {
          staffList.value[index] = updatedStaff;
        }
        return updatedStaff;
      } else {
        throw new Error(response.message || "更新员工信息失败");
      }
    } catch (err) {
      error.value = err.message || "更新员工信息失败";
      throw err;
    }
  };

  // 新增：更新员工信息（包含ID变更）
  const updateStaffWithNewId = async (oldId, newStaffData) => {
    try {
      const response = await updateStaff(newStaffData);
      if (response.code === 200) {
        const updatedStaff = response.data || newStaffData;

        // 找到原ID对应的员工索引
        const index = staffList.value.findIndex((staff) => staff.id === oldId);
        if (index !== -1) {
          // 更新员工数据
          staffList.value[index] = updatedStaff;
          // 更新当前选中的ID
          currentStaffId.value = updatedStaff.id;
        }
        return updatedStaff;
      } else {
        throw new Error(response.message || "更新员工信息失败");
      }
    } catch (err) {
      error.value = err.message || "更新员工信息失败";
      throw err;
    }
  };

  const deleteStaffData = async (staffId) => {
    try {
      const response = await deleteStaff(staffId);
      if (response.code === 200) {
        const index = staffList.value.findIndex(
          (staff) => staff.id === staffId
        );
        if (index !== -1) {
          staffList.value.splice(index, 1);

          if (staffList.value.length > 0) {
            currentStaffId.value = staffList.value[0].id;
          } else {
            currentStaffId.value = null;
          }
        }
        return true;
      } else {
        throw new Error(response.message || "删除员工失败");
      }
    } catch (err) {
      error.value = err.message || "删除员工失败";
      throw err;
    }
  };

  const setCurrentStaff = (staffId) => {
    currentStaffId.value = staffId;
  };

  const resetCurrentStaff = () => {
    if (staffList.value.length > 0) {
      currentStaffId.value = staffList.value[0].id;
    } else {
      currentStaffId.value = null;
    }
  };

  return {
    // State
    staffList,
    currentStaffId,
    isLoading,
    error,

    // Getters
    currentStaff,
    hasStaff,

    // Actions
    loadStaffList,
    addStaffLocal, // 新增：本地添加
    createStaffAPI, // 新增：API创建
    updateStaffData,
    updateStaffWithNewId, // 新增：带ID更新的方法
    deleteStaff: deleteStaffData,
    setCurrentStaff,
    resetCurrentStaff,
  };
});

export default useStaffStore;
